﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web.Mvc;
using Abam.Code.OAuth;

namespace Abam.Controllers
{
    public class AuthController : Controller
    {
        public ActionResult AuthorizeWithYandex()
        {
            return Redirect(YandexAuthorize.AuthorizeAddress);
        }

        public ActionResult AuthorizeWithGoogle()
        {
            return Redirect(GoogleAuthorize.AuthorizeAddress);
        }

        public ActionResult GetYandexToken()
        {
            try
            {
                var response = YandexAuthorize.GetToken(HttpContext.Request.Params["code"]);

                var sr = new StreamReader(response.GetResponseStream(), Encoding.ASCII);

                var yandexUser = YandexAuthorize.Deserialize(sr);

                MvcApplication.UserToken = yandexUser.Access_Token;

                MvcApplication.UserDisplayName = YandexAuthorize.Info(MvcApplication.UserToken).Display_name;

                sr.Close();
            }
            catch (Exception exception)
            {
                ViewData["Error"] = exception.InnerException + exception.Message;
                return View("Error");
            }
            return RedirectToAction("Index", "Home");
        }

        public ActionResult GetGoogleToken()
        {
            try
            {
                var response = GoogleAuthorize.GetToken(HttpContext.Request.Params["code"]);

                var sr = new StreamReader(response.GetResponseStream(), Encoding.ASCII);

                var user = GoogleAuthorize.Deserialize(sr);

                MvcApplication.UserToken = user.Access_Token;

                sr.Close();
            }
            catch (Exception exception)
            {
                ViewData["Error"] = exception.InnerException + exception.Message;
                return View("Error");
            }
            return RedirectToAction("Index", "Home");
        }

        public string GetUser()
        {
            return MvcApplication.UserDisplayName;
        }
    }
}
